import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { LoginResDto } from './dto/login-res.dto';
import { jwtConstants } from './constants';
@Injectable()
export class AuthService {
    constructor(private readonly userService: UserService) {}

    async login(username: string, password: string): Promise<[boolean, LoginResDto, string]> {
        let user = await this.userService.findOneByUsername(username);
        
        if(user[0]){
            let result = user[1];
            console.log(result);
            const data :any=  {};
            data.username = result.userName;
            data.userId = result.Id;
            data.roleId = result.Role == null ? '' : result.Role.Id;
            data.deptId = result.Dept == null ? '' : result.Dept.Id;
            data.tenantId = result.tenantId;
            data.realName = result.realName;
            data.avatar = result.avatar;
            if(bcrypt.compareSync(password, result.password)){
                const payload = { username: result.userName, sub: result.Id };
                data.token = await new JwtService().signAsync(data, {
                    secret: jwtConstants.secret,
                    expiresIn: '1h', // 设置过期时间
                })
                return [true, data, "验证成功"];
            } else {
                return [false, new LoginResDto, "用户名或密码错误"];
            }
        }else{
            return [false, new LoginResDto, "用户名或密码错误"];
        }
        
    }
}
